/**
 * 获取下发权限
 */
async function requestSubscribeMessage(templateId) {
    if (!templateId) {
        wx.showModal({
            title: '发送失败',
            content: '请先获取模板 ID',
            showCancel: false,
        })
        return
    }
    return new Promise((resolve, reject) => {
        wx.requestSubscribeMessage({
            tmplIds: [templateId],
            success: (res) => {
                if (res[templateId] === 'accept') {
                    resolve()
                } else {
                    reject()
                }
            },
            fail: (err) => {
                reject(err)
            },
        })
    })
}

/**
 * 发送订阅消息
 */
async function sendSubscribeMessage({
    templateId,
    data,
    id
}) {
    try {
        await requestSubscribeMessage(templateId) // requestSubscribeMessageResult
    } catch (e) {
        return Promise.reject(e)
    }
    return new Promise((resolve, reject) => {
        wx.cloud.callFunction({
            name: 'openapi',
            data: {
                action: 'sendSubscribeMessage',
                templateId,
                data,
                id
            },
            success: res => {
                wx.showModal({
                    title: '发送成功',
                    content: '请返回微信主界面查看',
                    showCancel: false,
                    success() {
                        resolve(res.result)
                    }
                })
            },
            fail: err => {
                wx.showToast({
                    icon: 'none',
                    title: '调用失败',
                })
                reject(err)
            }
        })
    })
}

module.exports = {
    sendSubscribeMessage
}